package in.muton.edushare.components.tasks.invitations.api;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.messaging.api.PollMessage;
import in.muton.edushare.url.EduShareURLPanel;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.List;

import com.edushare.common.dao.GroupsMembersDAO;
import com.edushare.common.dao.PollsDAO;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.GroupMembers;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.UserPoll;
import com.edushare.common.vo.Users;

public class GroupInvitations extends Invitation {

	private CayenneModel<GroupMembers> membership;

	public GroupInvitations(CayenneModel<GroupMembers> membership) {
		this.membership = membership;
	}

	@Override
	public void accept() {
		membership.getObject().setStatus(GroupMembers.STATUS_ACTIVE);
		EduShareSession.get().getSessionORMInterface().commitAllChanges();
		postInvitationTasks();
	}

	@Override
	public void decline() {
		new GroupsMembersDAO(EduShareSession.get().getSessionORMInterface())
				.remove(membership.getObject());
	}

	@Override
	public EduShareURLPanel getDestURL() {
		return new EduShareURLPanel("link", new CayenneModel<Groups>(membership
				.getObject().getGroup()));
	}

	@Override
	public void postInvitationTasks() {
		// 1.Add user to open polls.
		ORMInterface orm = EduShareSession.get().getSessionORMInterface();
		List<Poll> pollList = new PollsDAO(orm).getPollsByCreator(
				Messages.RECEIVER_TYPE_GROUP, membership.getObject().getGroup()
						.getGroupId());

		for (Poll p : pollList) {
			if (p.getStatus() == Poll.POLL_STATUS_POLLING) {
				new UserPollDAO(orm).addUserToPoll(membership.getObject()
						.getUser(), p, UserPoll.ROLE_RESPONDENT);
				CayenneList<Users> cl = new CayenneList<Users>(null);
				cl.add(membership.getObject().getUser());
				new PollMessage(p).setReciever(
						membership.getObject().getGroup()).setReciever(cl)
						.send();
			}
		}
	}

}
